<?php

/**
 * 接口基类
 * 作者：刘单风
 * 最后修改时间：2018-11-14
 * 版权：医库PHP小组
 */
namespace app\index\controller;
use app\model\Members;
use app\model\Util;
use MoCommon\Business\BizCodes;
use MoCommon\Support\EncryptTool;
use MoCommon\WeChat\Wx;
use think\Controller;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Cookie;
use MoCommon\Support\Codes;
use think\facade\Env;

class Apibase extends Controller
{
    /**
     * 获取用户id
     * @param int $type 0必须登录;1不登录也可以访问,用户id为0
     * @return int
     */
    protected function getUid($type=0)
    {
        $options = Config::get('app.converse');
        $redis = Cache::init($options);

        $userid = 0;
        if (($sign = input('user_sign')) && ($json_info = $redis->get($sign))) {

            $userid = json_decode($json_info, true)['id'];

        }
        if (($sign = Cookie::get('user_sign')) && ($json_info = $redis->get($sign))) {
            $userid = json_decode($json_info, true)['id'];
        }
        if (empty($userid)) {
            if ($type) {
                return 0;
            } else {
                //用户未登录
                $result = array(
                    'status' => Codes::NO_SIGNIN,
                    'msg' => Codes::get(Codes::NO_SIGNIN),
                    'data' => []
                );
                echo json_encode($result);
                exit;
            }

        } else {
            return $userid;
        }
    }
    /**
     * 获取用户信息, 原理同上.
     *
     * @return array
     *
     * @farwish
     */
    protected function userInfo()
    {
        $options = Config::get('app.converse');
        $redis = Cache::init($options);
        $sign = Cookie::get('user_sign');
        $json_info = $redis->get($sign);
        if ($sign && $json_info) {
            return json_decode($json_info, true);
        }

        return [];
    }


    /**
     * 响应格式.
     *
     */
    public function respond($content = null, $status = '', $msg = '')
    {
        $result = [
            'status' => $status ?: Codes::ACTION_SUC,
            'msg' => $msg ?: Codes::get(Codes::ACTION_SUC),
            'data' => $content
        ];
        return json($result);
    }


    protected function full_info($user_id = 0)
    {
        if ($user_id == 0) {
            $user_info = $this->userInfo();
            $openid = isset($user_info['openid']) ? $user_info['openid'] : 0;

            if ((!$openid) && $user_info) {
                $member = Members::findMembers(["id"=>$user_info['id']]);
                $openid = $member ? $member['openid'] : '';

            }
        } else {
            $member = Members::findMembers(["id"=>$user_id]);
            $openid = $member ? $member['openid'] : '';
        }

        $wechat = Config::get('app.wechat');

        Wx::init([$wechat['appid'], $wechat['secret']]);

        // 获取基础 access_token

        $access_token = Util::get_access_token();

        $full_info = Wx::cgi_userinfo($access_token, $openid);

        //access_token 过期处理
        if (!empty($full_info['errcode']) && $full_info['errcode'] == 40001) {

            $access_token = Util::update_access_token();
            $full_info = Wx::cgi_userinfo($access_token, $openid);
        }


        $full_info['subscribe'] = empty($full_info['subscribe']) ? 0 : $full_info['subscribe'];

        return $full_info;

    }

    ///获取网站配置信息
    public function get_website_config()
    {
        $website = Config::get('app.website');
        return $website;
    }

    //验签
    public function sign_validate()
    {
        $website = self::get_website_config();
        $rootpath=Env::get('vendor_path');
        $sign = input('sign');
        $timestamp = input('timestamp');
        $dedata=EncryptTool::data_openssl_private_decode($rootpath,$sign);
        $ownsign = $website['secretkey'] . $timestamp;
        if ($dedata != $ownsign) {
            //验签失败
            $result = array(
                'status' => Codes::ACTION_ILL,
                'msg' => Codes::get(Codes::ACTION_ILL),
                'data' => []
            );
            echo json_encode($result);
            exit;
        }
    }

    /**
     * 简单词/敏感词简单检测.
     *
     * @param string $words
     * @return bool
     *
     * @farwish
     */
    protected static function badCheck($words)
    {
        $simple = [
            ',',
            '.',
            '。',
            '学习',
            '学习。',
            '学习了',
            '学习了。',
            '支持',
            '支持。',
            '不错',
            '不错。',
            '同意',
            '同意。',
            '赞',
            '赞。',
            '赞同。',
            '不知道',
            '不知道。',
            '有道理',
            '有道理。',
        ];

        $status = 0;

        if (in_array($words, $simple)) {
            $status = BizCodes::SIMPLE_WORDS;
        }
        $msg = BizCodes::get($status);

        return ['status' => $status, 'msg' => $msg];
    }

}